<template>
    <el-card class="box-card">
        <el-row>
            <el-col :span="5">
                <el-input v-model="searchVal" placeholder="Please input" @change="Search" />
            </el-col>
            <el-col :span="12">
                <el-button type="primary" @click="Search">查询</el-button>
                <el-button type="primary" @click="open">新增</el-button>
                <el-button type="primary" @click="opensetting">分配菜单</el-button>
            </el-col>
        </el-row>
        <br>
        <el-row>
            <el-col>
                <el-table :data="tableData" style="width: 100%; height: 65vh;" border row-key="id" ref="tb">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="RoleName" label="角色名称" width="180" />
                    <el-table-column prop="IsEnable" label="是否启用">
                        <template #default="scope">
                            <el-switch v-model="scope.row.IsEnable" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column prop="Description" label="描述" />
                    <el-table-column prop="Order" label="序号" width="60" />
                    <el-table-column prop="CreateDate" label="创建时间" width="180" />
                    <el-table-column lable="Operations" align="center">
                        <template #default="scope">
                            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                            <el-button size="small" type="danger" @click="handleDel(scope.row.Id)">Delete</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
            <el-pagination style="margin-top: 20px;" v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="totalCount" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-row>
    </el-card>
    <Add :isShow="isShow" :info="info" @closeAdd="closeAdd" @success="success"></Add>
    <Setting :isShow="isShowSet" :rid="rid" @closeSetting="closeSetting" @saveSetting="saveSetting"></Setting>
</template>
  
<script lang="ts" setup>
import { Ref, onMounted, ref } from 'vue'
import Role from '../../../class/Role';
import Add from './Add.vue'
import Setting from './setting.vue'
import { ElMessage, ElTable, ElMessageBox } from 'element-plus'
import { delRole, getRoles } from '../../../http';
const tableData: Ref<Array<Role>> = ref<Array<Role>>([])
const searchVal = ref('')
const currentPage = ref(1) //前往多少页
const pageSize = ref(10) //默认页数大小
const totalCount = ref(0)
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
let parms = ref({
    Name: "",
    Index: "",
    FilePath: "",
    Description: "",
    pageIndex: currentPage,
    pageSize: pageSize
})
const load = async () => {
    parms.value.Name = searchVal.value
    let res = await getRoles(parms.value) as any
    tableData.value = res.Data
    totalCount.value = res.Total
}
const Search = async () => { await load() }
onMounted(() => { load() })
const handleSizeChange = async (val: number) => {
    await load()
    console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
    await load()
    console.log(`current page: ${val}`)
}
//------- 新增/修改/删除逻辑 --------
const isShow = ref(false)
const info: Ref<Role> = ref<Role>(new Role())
const open = () => {
    isShow.value = true
}
const closeAdd = () => {
    isShow.value = false
    info.value = new Role
}
const handleEdit = (index: number, row: Role) => {
    console.log(index)
    console.log(row)
    info.value = row
    isShow.value = true
}
const success = async (message: string) => {
    isShow.value = false
    info.value = new Role()
    ElMessage.success(message)
    await load()
}
const handleDel = async (id: string) => {
    ElMessageBox.confirm("确认要删除这条数据吗？", "删除提示", {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
    }).then(async () => {
        var res = await delRole(id)
        if (res) {
            await load()
            ElMessage({ type: 'success', message: '删除成功！' })
        } else {
            ElMessage({ type: 'error', message: '删除失败!' })
        }
    }).catch(() => { })
}

//------分配菜单------
const rid = ref("")
const tb = ref<InstanceType<typeof ElTable>>()
const isShowSet = ref(false)
const opensetting = () => {
    let rows = tb.value?.getSelectionRows()
    if (rows.length == 1) {
        isShowSet.value = true
        rid.value = tb.value?.getSelectionRows().map((item: any) => item.Id).join(",")
        console.log(`打开了role设置页面：show:${isShowSet.value} rid:${rid.value}`)
    } else if (rows.length > 1) {
        ElMessage.warning("请选择单个操作!")
    } else {
        ElMessage.warning("请选择需要分配菜单的角色")
    }
}
const closeSetting = () => {
    isShowSet.value = false
    console.log(`关闭了setting页面，值为：${isShowSet.value}`)
}
const saveSetting = () => {
    isShowSet.value = false
    console.log(`关闭了setting页面，值为：${isShowSet.value}`)
}
</script>
  